<template>
  <view class="page">
    <view v-if="$data.info">
      <!-- 地址 -->
      <!-- <view class="address" @tap="onCheckAddress">
        <view class="address_left">
          {{ $data.address || "请选择服务地址" }}
        </view>
        <view class="address_right">
          <image :src="ImgIconRightGray" />
        </view>
      </view> -->
      <!-- 产品详情 -->
      <view class="detail">
        <view class="detail_img">
          <image :src="$data.info._picurl" />
        </view>
        <view class="detail_content">
          <view class="detail_content--title">
            {{ $data.info.serviceTitle }}
          </view>
          <view class="detail_content--desc">
            已选：
            {{ $data.info.serviceTitle }}
          </view>
          <view class="detail_content--price text-price">
            {{ $data.info.totalPrice }}
          </view>
        </view>
      </view>
      <!-- 地址 -->
      <view class="address margin-top" @tap="onCheckAddress">
        <view class="address_left">
          {{ $data.address || "请选择服务地址" }}
        </view>
        <view class="address_right">
          <image :src="ImgIconRightGray" />
        </view>
      </view>
      <!-- 服务时间 -->
      <view class="time">
        <view class="time_title">服务时间</view>
        <view class="time_content" @tap="() => ($data.chooseTimeShow = true)">
          <view class="time_content--check">
            <text v-if="$data.time" class="text-main-color">
              {{ $data.time }}
            </text>
            <text v-else class="text-gray">请添加服务时间</text>
          </view>
          <view class="time_content--icon">
            <image :src="ImgIconRightGray" />
          </view>
        </view>
      </view>
      <!-- 劳动者 -->
      <view class="worker" v-if="$data.showWorkerRow">
        <view class="worker_title">劳动者</view>
        <view class="worker_content" @tap="onCheckWorker">
          <view class="worker_content--check">
            <text v-if="params.workerId" class="text-main-color">
              {{ $data.workerName }}
            </text>
            <text v-else class="text-gray">请选择劳动者</text>
          </view>
          <view class="worker_content--icon">
            <image :src="ImgIconRightGray" />
          </view>
        </view>
      </view>
      <!-- 优惠券 -->
      <!-- <view class="coupon">
          <view class="coupon_title">优惠券</view>
          <view class="coupon_content" @tap="onCheckCoupon">
            <view class="coupon_content--check">
              <text v-if="$data.couponName" class="text-main-color">
                {{ $data.couponName }}
              </text>
              <text v-else class="text-gray">
                <text v-if="$data.couponCanUseCount > 0">
                  有{{ $data.couponCanUseCount }}张优惠券可使用
                </text>
                <text v-else>暂无可用优惠券</text>
              </text>
            </view>
            <view class="coupon_content--icon">
              <image :src="ImgIconRightGray" />
            </view>
          </view>
        </view> -->
      <!-- 备注 -->
      <view class="card margin-top">
        <view class="card_title margin-bottom">备注</view>
        <up-textarea
          v-model="params.remark"
          placeholder="如有其他要求请备注"
          :height="100"
          :maxlength="150"
          border="surround"
          count
        ></up-textarea>
      </view>
      <!-- 温馨提示 -->
      <!-- <view class="card margin-top">
        <up-parse :content="$data.tips"></up-parse>
      </view> -->
      <!-- 底部结算按钮 -->
      <view class="foot foot_box">
        <!-- <view class="btn btn_cancel" @tap="onApply">申请退款</view> -->
        <mg-pay-button
          :mode="sdkData.mode"
          :orderId="sdkData.orderId"
          :orderStatus="sdkData.orderStatus"
          :refundId="sdkData.refundId"
          :refundTotalAmount="sdkData.refundTotalAmount"
          :applyRefundParams="sdkData.applyRefundParams"
          :localNo="$data.localNo"
          :douYinPayJson="$data.douYinPayJson"
          :workSecondPrice="$data.workSecondPrice"
        ></mg-pay-button>
        <view class="btn btn_save" @tap="onSave">预约</view>
      </view>
    </view>
    <PopupChooseTime
      v-model:show="$data.chooseTimeShow"
      :nowDay="$data.nowDate"
      @confirm="onChooseTime"
    />
    <PopupGoldWorker
      v-model:show="$data.chooseWorkerShow"
      :params="{
        userAddressId: params.userAddressId,
        firstStartServicedAt: $data.timeStamp,
        orderServiceId: $data.info?.orderServiceId,
      }"
      :currentWorkerId="params.workerId"
      @confirm="onGoldWorkerConfirm"
    />
    <PopupLogin />
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, nextTick } from "vue";
import { onLoad, onShow, onReady, onUnload } from "@dcloudio/uni-app";
import BasicConfig from "@/utils/config";
import { eventBus } from "../../../enums/eventBus";
import { skuInputType } from "../../../enums/sku";
import { useGetLocationStorage } from "../../../hooks/useStorage";
import {
  freePay,
  getOrderDetail,
  orderConfirm,
  orderImmediate,
  refundOrderDetail,
  subscribeOrder,
} from "../../../api/Interface/order";
import errorCode from "../../../utils/http/errorCode";
import { ImgIconRightGray } from "../../../utils/iconMap";
import { jumpPage } from "../../../utils/route/route";
import PopupChooseTime from "./components/PopupChooseTime.vue";
import { couponTypeConfig, couponUseTypeConfig } from "../../../enums/coupon";
import {
  orderRefundStatusConfig,
  orderSourceType,
  orderStatus,
  orderType,
  payType,
} from "../../../enums/order";
import { useLakalaPay, usePayment, useWechatPay } from "../../../hooks/usePay";
import { useImgSrc } from "../../../hooks/useImg";
import { useSubscribeTemplate } from "../../../hooks/useSubscribe";
import { subscribeEnum } from "../../../enums/subscribe";
import { useGetConfig } from "../../../hooks/useCommon";
import { configKeyEnum } from "../../../enums/common";
import { getServiceDetail } from "../../../api/Interface/service";
import { useUpdateRefund } from "../../../hooks/useOrder";
import PopupGoldWorker from "../../components/PopupGoldWorker.vue";
import { getGoldWorkerList } from "../../../api/Interface/worker";
import {
  useGetAuthLocation,
  useGetLocationAddress,
} from "../../../hooks/useLocation";
import dayjs from "dayjs";

const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $data = reactive({
  address: "", // 选择的地址
  info: null,
  time: "", // 选择的服务时间
  timeStamp: 0, // 选择的服务时间时间戳
  chooseTimeShow: false, // 选择日期
  message: "",
  buying: false, // 预约中 不可重复预约
  douYinPayJson: null, // 抖音退款
  workSecondPrice: 0,
  showWorkerRow: false,
  workerName: null,
  chooseWorkerShow: false, // isDev ? true :
  workerErrorDesc: "", // 劳动者冲突提示
  firstJoin: true, // 首次进入页面
  nowDate: dayjs(), // 当前日期
  timer: null,
});
const params = reactive({
  localNo: "",
  domesticServiceId: "", // 服务技能id
  userAddressId: "", // 地址ID
  firstStartServicedAt: 0, // 服务时间【十位时间戳】
  remark: "", // 备注
  workerId: null,
});
const sdkData = reactive({
  mode: 1, // 组件使用模式 1.已下单 2.未下单
  orderStatus: 1, // mode为1时, 0：继续支付 ,1：申请退款,2：退款中,3：退款成功 ,4：退款失败
  orderId: "", // 开发者订单系统的交易订单号
  refundId: "", // 开发者订单系统的退款单号，用于查看退款详情； orderStatus为2,3,4时必传
  refundTotalAmount: 0, // 针对交易系统之前的老订单申请退款
  applyRefundParams: null, // 退款参数（仅uniapp或taro开发需要，原生抖音小程序不需要）
});
const init = async () => {
  $data.timer = setInterval(() => {
    $data.nowDate = dayjs();
  }, 6000 * 10);

  // 选择地址通信
  uni.$on(eventBus.service.address, async (e) => {
    $data.address = e.address;
    params.userAddressId = e.userAddressId;
    console.log("选择地址通信", e);
    await getData();
    await getWorkerList();
  });
  // await getData();
};
const clearTimer = () => {
  clearInterval($data.timer);
  $data.timer = null;
};
/** 初始化数据 */
const getData = async () => {
  $data.message = "数据加载中...";
  useUpdateRefund({
    localNo: params.localNo,
    orderServiceId: $data.orderServiceId,
  }).then((res) => {
    console.log("useUpdateRefund", res);
    if (res.code === errorCode.success) {
      $data.douYinPayJson = res.data.douYinPayJson;
      $data.workSecondPrice = res.data.workSecondPrice;
      sdkData.orderStatus = res.data._orderStatus;
      sdkData.refundId = res.data.localNo;
      if ($data.douYinPayJson) {
        sdkData.refundTotalAmount = $data.douYinPayJson.total_amount;
      }
    }
  });
  await getOrderDetail({
    orderServiceId: params.localNo,
  }).then((res) => {
    if (res.code === errorCode.success) {
      $data.info = res.data;
      if ($data.info) {
        $data.info._picurl = useImgSrc($data.info.picurl);
        $data.info.addressSnapshot = $data.info.addressSnapshot ?? {};
        sdkData.orderId = $data.info.localNo;
        $data.showWorkerRow =
          $data.info.serviceSnapshot && $data.info.serviceSnapshot.isGold == 1;
        if ($data.showWorkerRow) {
          if (!params.workerId) {
            params.workerId = $data.info.workerId;
            $data.workerName = $data.info.workerDetail?.nickname;
          }
          // if (!$data.info.workerId) {
          //   params.workerId = null;
          //   $data.workerName = null;
          // }
        }
      }
    }
  });
  $data.message = "";
};
const getWorkerList = async () => {
  if (!$data.showWorkerRow) return;
  if (!params.userAddressId) return;
  if (!$data.timeStamp) return;
  BasicConfig.loadToast();
  await getGoldWorkerList({
    userAddressId: params.userAddressId,
    firstStartServicedAt: $data.timeStamp,
    orderServiceId: $data.info.orderServiceId,
    workerId: params.workerId,
  }).then((res) => {
    if (res.code === errorCode.success) {
      if (!res.data || res.data.length === 0) {
        params.workerId = null;
        $data.workerName = null;
        return;
      }
      // isConflict 0.无冲突 1.有冲突
      if (res.data[0].isConflict == 1 && params.workerId) {
        $data.workerErrorDesc =
          "由于时间冲突当前劳动者无法选择，请选择其他劳动者";
        uni.showModal({
          content: $data.workerErrorDesc,
          showCancel: false,
          confirmText: "确认",
          confirmColor: BasicConfig.MainColor,
          success: (success) => {
            $data.workerErrorDesc = "";
            params.workerId = null;
            $data.workerName = null;
          },
        });
      } else {
        // if (isDev) {
        //   $data.workerErrorDesc =
        //     "由于时间冲突当前劳动者无法选择，请选择其他劳动者 test";
        //   uni.showModal({
        //     content: $data.workerErrorDesc,
        //     showCancel: false,
        //     confirmText: "确认",
        //     confirmColor: BasicConfig.MainColor,
        //     success: (success) => {
        //       $data.workerErrorDesc = "";
        //       params.workerId = null;
        //       $data.workerName = null;
        //     },
        //   });
        // }
      }
    } else {
      params.workerId = null;
      $data.workerName = null;
    }
  });
  uni.hideLoading();
};
const onCheckWorker = () => {
  if (!$data.showWorkerRow) return;
  if (!params.userAddressId) {
    BasicConfig.toast("请先选择服务地址");
    return;
  }
  if (!$data.timeStamp) {
    BasicConfig.toast("请先选择服务时间");
    return;
  }
  $data.chooseWorkerShow = true;
};
// 劳动者选择组件回调
const onGoldWorkerConfirm = (e) => {
  console.log("onGoldWorkerConfirm", e);
  if (!e) return;
  const { isConflict, nickname, workerId } = e;
  // 不冲突,直接选择
  if (isConflict == 0) {
    $data.workerName = nickname;
    params.workerId = workerId;
  }
  // 冲突,选择日期
  else {
    $data.chooseTimeShow = true;
    $data.workerName = nickname;
    params.workerId = workerId;
  }
};
const onCheckAddress = () => {
  jumpPage({
    to: "/package-my/pages/addressManage/index",
    query: {
      fromType: eventBus.service.address,
    },
  });
};
const onChooseTime = async (e) => {
  if (!e) return;
  const { time, label } = e;
  $data.timeStamp = time;
  $data.time = label;
  await getData();
  await getWorkerList();
};
const onChooseTimeClose = (e) => {
  console.log("onChooseTimeClose", e);
  if (!$data.timeStamp) {
    $data.workerName = null;
    params.workerId = null;
  }
};
/** 预约 */
const onSave = async () => {
  if ($data.buying) {
    return;
  }
  if (!$data.timeStamp) {
    BasicConfig.toast("您尚未添加服务时间，请添加服务时间后提交订单");
    return;
  }
  if (!params.userAddressId) {
    BasicConfig.toast("您尚未选择服务地址，请选择服务地址后提交订单");
    return;
  }
  const can = uni.canIUse("createOrder");
  console.log("can", can, tt, uni.createOrder);
  if (!can) {
    BasicConfig.toast("当前版本不支持创建订单，请升级到最新版本");
    return;
  }
  $data.buying = true;
  BasicConfig.loadToast("预约中...");
  params.firstStartServicedAt = $data.timeStamp;
  console.log("预约params", params);
  await subscribeOrder(params)
    .then((res) => {
      BasicConfig.toast(res.msg);
      if (res.code === errorCode.success) {
        setTimeout(() => {
          // uni.navigateBack({
          //   delta: 1,
          // });
          jumpPage({
            to: `/package-service/pages/order/order`,
            mode: "reLaunch",
          });
        }, 1500);
      } else {
        $data.buying = false;
      }
    })
    .catch((_) => {
      uni.hideLoading();
      $data.buying = false;
    });
};
/** 申请退款 */
const onApply = () => {
  jumpPage({
    to: "/package-service/pages/order/afterSales/apply",
    query: {
      localNo: params.localNo,
      orderServiceId: $data.info?.orderServiceId,
    },
  });
};
onLoad(async (options) => {
  $data.firstJoin = true;
  params.domesticServiceId = options.id;
  params.localNo = options.localNo;
  $data.buying = false;
  const LocationStorage = useGetLocationStorage() || {
    name: "未获取定位",
    code: null,
  };
  const auth = await useGetAuthLocation();
  if (!LocationStorage?.code || !auth) {
    try {
      await useGetLocationAddress().then((res) => {
        loadData();
      });
    } catch (error) {
      loadData();
    }
  } else {
    loadData();
  }
});
const loadData = async () => {
  setTimeout(async () => {
    await init();
    await getData();
    $data.firstJoin = false;
  }, 100);
};
onShow(() => {
  if (!$data.firstJoin) {
    nextTick(() => {
      getData();
    });
  }
});
onReady(() => {});
onUnload(() => {
  // uni.$off(eventBus.service.confirm);
  uni.$off(eventBus.service.address);
  clearTimer();
});
</script>
<style lang="scss" scoped>
.page {
  background: #f7f8fa;
  width: 100vw;
  min-height: 100vh;
  font-size: 32rpx;
  .address {
    background: #ffffff;
    display: flex;
    align-items: center;
    padding: 30rpx;
    &_left {
      width: calc(100% - 16rpx);
      padding-right: 30rpx;
    }
    &_right {
      width: 16rpx;
      height: 30rpx;
      image {
        width: 100%;
        height: 100%;
      }
    }
  }
  .detail {
    background: #ffffff;
    padding: 30rpx;
    display: flex;
    align-items: center;
    margin-top: 30rpx;
    &_img {
      width: 160rpx;
      height: 160rpx;
      image {
        width: 100%;
        height: 100%;
        border-radius: 20rpx;
      }
    }
    &_content {
      width: calc(100% - 160rpx);
      padding-left: 30rpx;
      // display: flex;
      // flex-direction: column;
      // justify-content: space-between;
      height: 100%;
      &--title {
        font-size: 36rpx;
        font-weight: 700;
      }
      &--desc {
        color: #666666;
        font-size: 34rpx;
        margin: 20rpx 0;
      }
      &--price {
        font-size: 34rpx;
        color: $main-color;
      }
    }
  }
  .time {
    padding: 30rpx;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;
    &_time {
      font-size: 34rpx;
      color: #333333;
    }
    &_content {
      display: flex;
      align-items: center;
      &--check {
        font-size: 34rpx;
      }
      &--icon {
        width: 16rpx;
        height: 30rpx;
        margin-left: 20rpx;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .worker {
    padding: 30rpx;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;
    &_time {
      font-size: 34rpx;
      color: #333333;
    }
    &_content {
      display: flex;
      align-items: center;
      &--check {
        font-size: 34rpx;
      }
      &--icon {
        width: 16rpx;
        height: 30rpx;
        margin-left: 20rpx;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .worker-error {
    background: #ffffff;
    text-align: right;
    color: red;
    padding: 30rpx;
  }
  .coupon {
    padding: 30rpx;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;
    &_time {
      font-size: 34rpx;
      color: #333333;
    }
    &_content {
      display: flex;
      align-items: center;
      &--check {
        font-size: 34rpx;
      }
      &--icon {
        width: 16rpx;
        height: 30rpx;
        margin-left: 20rpx;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .foot_box {
    padding: 30rpx;
    z-index: 9;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .bill {
      font-size: 34rpx;
      display: flex;
      align-items: center;
    }
    .btn {
      width: 50%;
      padding: 30rpx;
      border-radius: 100rpx;
      text-align: center;
      font-size: 34rpx;
    }
    .btn_save {
      background: $main-color;
      color: #ffffff;
    }
  }
}
</style>
